﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Sql;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CodeGenerator.Core;

namespace CodeGenerator
{
    public partial class frmSqlConnectionWizard : Form
    {
        SqlDataSourceEnumerator servidores;
        System.Data.DataTable TableServers;
        String servidor;
        bool serversLoaded = false;
        public delegate void selectedConnectionString(string connectionString);
        public event selectedConnectionString OnConnectionStringBuilt;
        
        public frmSqlConnectionWizard()
        {
            InitializeComponent();
            cboAuthetification.SelectedIndex = 0;
            cboServer.Items.Add("--Select server--");
        }

        private void GetServers()
        {
            servidores = SqlDataSourceEnumerator.Instance;
            TableServers = new DataTable();
            List<String> list = new List<string>();
            TableServers = servidores.GetDataSources();
            list.Add("--Select server--");

            foreach (DataRow rowServidor in TableServers.Rows)
            {
                string server = rowServidor["ServerName"].ToString();
                if (String.IsNullOrEmpty(rowServidor["InstanceName"].ToString()))
                    list.Add(rowServidor["ServerName"].ToString());
                else
                    list.Add(rowServidor["ServerName"] + "\\" + rowServidor["InstanceName"]);
            }
            cboServer.DataSource = list;
        }
        public void GetBases()
        {
            string select;
            string cadenaConexion;
            List<String> listaBasesdatos = new List<string>();
            listaBasesdatos.Add("--Select database--");
            if(cboAuthetification.SelectedItem.ToString()=="Windows")
                cadenaConexion = ";Data Source=" + this.servidor + ";Integrated Security=True;Initial Catalog=master";
            else 
                cadenaConexion = ";Data Source=" + this.servidor + ";user=" + txtUser.Text  + ";Password=" + txtPass.Text;
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(cadenaConexion);
            try
            {
                con.Open();
                chkIsRuning.Checked = true;
            }
            catch
            {
                MessageBox.Show("Failed server status");
                return;
            }
            select = "select name from sys.databases;";
            System.Data.SqlClient.SqlCommand com =
                             new System.Data.SqlClient.SqlCommand(select, con);
            System.Data.SqlClient.SqlDataReader dr = com.ExecuteReader();
            while (dr.Read())
            {
                listaBasesdatos.Add(dr[0].ToString());
            }
            dr.Close();
            select = "SELECT @@VERSION";
            System.Data.SqlClient.SqlCommand comVersion =
                             new System.Data.SqlClient.SqlCommand(select, con);
            System.Data.SqlClient.SqlDataReader drVersion = comVersion.ExecuteReader();
            while (drVersion.Read())
            {
                txtSqlVersion.Text = drVersion[0].ToString();
            }
            drVersion.Close();
            cboBases.DataSource = listaBasesdatos;
            con.Close();
        }
        public void GetBasesSelect()
        {
            string cadenaConexion = string.Empty;
            if (cboAuthetification.SelectedItem.ToString() == "Windows")
                cadenaConexion = "Data Source=" + this.servidor + ";Integrated Security=True;Initial Catalog=" + cboBases.SelectedItem.ToString() + ";";
            else
                cadenaConexion = "Data Source=" + this.servidor + ";user=" + txtUser.Text + ";Password=" + txtPass.Text + ";Initial Catalog=" + cboBases.SelectedItem.ToString() + ";";
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(cadenaConexion);
            try
            {
                con.Open();
                chkIsRuning.Checked = true;
            }
            catch(Exception ex)
            {

                MessageBox.Show("Failed login" + ex.Message);
                return;

            }
            con.Close();
            cadenaConexion += cadenaConexion + ";Application Name=" + ProjectConfiguration.ProjectName + ";";
            txtConnectString.Text = cadenaConexion;
        }
        private void cboServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            servidor = cboServer.SelectedValue.ToString();
            txtPass.Text = String.Empty;
            txtSqlVersion.Text = String.Empty;
            txtUser.Text = string.Empty;
            chkIsRuning.Checked = false;
            cboBases.DataSource = null;
            cboBases.Items.Insert(0, "--Select database--");
            cboBases.SelectedIndex = 0;
            txtConnectString.Text = String.Empty;
            cboAuthetification.SelectedIndex = 0;
        }

        private void cboAuthetification_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtPass.Text = String.Empty;
            txtSqlVersion.Text = String.Empty;
            txtUser.Text = string.Empty;
            chkIsRuning.Checked = false;
            cboBases.DataSource = null;
            cboBases.Items.Insert(0, "--Select database--");
            cboBases.SelectedIndex = 0;
            txtConnectString.Text = String.Empty;
  
            if (cboAuthetification.SelectedIndex > 0)
            {
                if (cboAuthetification.SelectedItem.ToString() == "SQL Server")
                {
                    txtPass.Enabled = true;
                    txtUser.Enabled = true;
                }
                else
                {
                    txtPass.Enabled = false;
                    txtUser.Enabled = false;
                }
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            if (cboServer.Text != String.Empty )
            {
                if (cboServer.Text != "--Select server--")
                {
                    if (cboAuthetification.SelectedIndex > 0)
                    {
                        if (cboAuthetification.SelectedItem.ToString() != "Windows")
                        {
                            if (txtUser.Text == String.Empty)
                            {
                                errorProviderUserName.SetError(txtUser, "Username is required");
                                return;

                            }
                            if (txtPass.Text == String.Empty)
                            {
                                errorProviderPass.SetError(txtPass, "Password is required");
                                return;
                            }
                        }
                        GetBases();
                    }
                    else
                        MessageBox.Show("Select authentication type");
                }
                else
                    MessageBox.Show("Select server");
            }
            else
                MessageBox.Show("Select server");
        }

        private void cboServer_TextChanged(object sender, EventArgs e)
        {
            servidor = cboServer.Text;
            txtPass.Text = String.Empty;
            txtSqlVersion.Text = String.Empty;
            txtUser.Text = string.Empty;
            chkIsRuning.Checked = false;
            cboBases.DataSource = null;
            cboBases.Items.Insert(0, "--Select database--");
            cboBases.SelectedIndex = 0;
            txtConnectString.Text = String.Empty;
            cboAuthetification.SelectedIndex = 0;
        }

        private void btnTestUserDb_Click(object sender, EventArgs e)
        {
            if (cboBases.SelectedIndex > 0)
                GetBasesSelect();
            else
                MessageBox.Show("Select database" );
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //Clipboard.SetDataObject(txtConnectString.Text, true);
            if (OnConnectionStringBuilt != null)
                OnConnectionStringBuilt.Invoke(txtConnectString.Text);
            this.Close();
        }

        private void cboBases_Click(object sender, EventArgs e)
        {
            txtConnectString.Text = String.Empty;
        }

        private void cboServer_Click(object sender, EventArgs e)
        {
            if (!serversLoaded)
            {
                GetServers();
                serversLoaded = true;
            }
        }

        private void cboBases_SelectedIndexChanged(object sender, EventArgs e)
        {
            ProjectConfiguration.DatabaseName = cboBases.Text.Trim();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
    }
}
